package com.hjrpc.babyyamall.authserver.web;

import com.google.gson.Gson;
import com.hjrpc.babyyamall.authserver.feign.MemberFeignService;
import com.hjrpc.babyyamall.authserver.service.RegisterService;
import com.hjrpc.babyyamall.authserver.vo.UserRegisterVo;
import com.hjrpc.common.constant.AuthServerConstant;
import com.hjrpc.common.dto.MemberRegisterTo;
import com.hjrpc.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Validated
public class RegisterController {

    @Autowired
    RegisterService registerService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/register.html")
    public String registerHtml(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            return "redirect:http://babyyamall.com";
        }
        return "register";
    }

    @RequestMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone")
                      @Pattern(regexp = "^[1][3-8]\\d{9}$", message = "手机号不合法")
                              String phone) {
        return registerService.sendCode(phone);
    }

    @PostMapping("/register")
    public String register(@Validated UserRegisterVo userRegisterVo, BindingResult bindingResult,
                           RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            // 如果key重复，则将value拼接
            Map<String, String> errors = bindingResult.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (v1, v2) -> v1 + "," + v2));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 回显先不开发了
//            redirectAttributes.addFlashAttribute(userRegisterVo);
            System.out.println(errors);
            return "redirect:http://auth.babyyamall.com/register.html";
        }

        // 判断验证码是否正确
        String codeWithTime = stringRedisTemplate.opsForValue().get(AuthServerConstant.AUTH_REDIS_PREFIX + userRegisterVo.getPhone());
        if (StringUtils.isBlank(codeWithTime) || !userRegisterVo.getCode().equalsIgnoreCase(codeWithTime.split("_")[0])) {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.babyyamall.com/register.html";
        }

        // 远程调用会员服务注册
        MemberRegisterTo memberRegisterTo = new MemberRegisterTo();
        BeanUtils.copyProperties(userRegisterVo, memberRegisterTo);
        R registerResult = memberFeignService.register(memberRegisterTo);

        if (!registerResult.isSuccess()) {
            redirectAttributes.addFlashAttribute("errors",
                    new Gson().fromJson((String) registerResult.get("errors"), Map.class));
            return "redirect:http://auth.babyyamall.com/register.html";
        }

        // redis中删除code
        stringRedisTemplate.delete(AuthServerConstant.AUTH_REDIS_PREFIX + userRegisterVo.getPhone());
        return "login.html";
    }
}
